import React, { useState, useEffect } from 'react';
import { Card, Button, Space, message, Typography, Row, Col } from 'antd';
import { menuAPI, authAPI } from '../utils/api';

const { Title } = Typography;

const FixedMenuPage = () => {
  const [isLoggedIn, setIsLoggedIn] = useState(!!localStorage.getItem('admin_token'));
  const [loginForm, setLoginForm] = useState({ email: '', password: '' });
  const [loginLoading, setLoginLoading] = useState(false);
  const [menuItems, setMenuItems] = useState([]);
  const [loading, setLoading] = useState(false);
  
  // 处理登录
  const handleLogin = async () => {
    setLoginLoading(true);
    try {
      console.log('登录表单数据:', loginForm);
      const response = await authAPI.login(loginForm);
      console.log('登录响应:', response);
      
      if (response.data && response.data.data && response.data.data.token) {
        const { token } = response.data.data;
        localStorage.setItem('admin_token', token);
        message.success('登录成功');
        setIsLoggedIn(true);
      } else {
        message.error(response.data?.message || '登录失败');
      }
    } catch (error) {
      console.error('登录错误:', error);
      message.error(error.response?.data?.message || '登录时发生错误');
    } finally {
      setLoginLoading(false);
    }
  };
  
  // 处理登出
  const handleLogout = () => {
    localStorage.removeItem('admin_token');
    setIsLoggedIn(false);
    message.success('已退出登录');
  };
  
  // 获取菜单数据
  useEffect(() => {
    const fetchMenuItems = async () => {
      if (!isLoggedIn) return;
      
      try {
        setLoading(true);
        const response = await menuAPI.getMenuItems();
        console.log('菜单API响应:', response);
        
        if (response.data && response.data.success && response.data.data && response.data.data.items) {
          // 确保每个菜单项的所有属性都是可渲染的
          const safeMenuItems = response.data.data.items.map(item => ({
            ...item,
            // 确保所有可能是对象的字段都被转换为字符串
            name: String(item.name || ''),
            description: String(item.description || ''),
            category: String(item.category || ''),
            price: typeof item.price === 'number' ? item.price : 0,
            originalPrice: typeof item.originalPrice === 'number' ? item.originalPrice : 0,
            stock: typeof item.stock === 'number' ? item.stock : 0,
            sales: typeof item.sales === 'number' ? item.sales : 0,
            status: String(item.status || 'unavailable'),
            isHot: !!item.isHot,
            isNew: !!item.isNew
          }));
          
          setMenuItems(safeMenuItems);
          console.log('菜单数据已更新:', safeMenuItems);
        } else {
          console.warn('菜单API响应格式异常:', response);
          setMenuItems([]);
        }
      } catch (error) {
        console.error('获取菜单数据失败:', error);
        message.error('获取菜单数据失败');
        setMenuItems([]);
      } finally {
        setLoading(false);
      }
    };
    
    fetchMenuItems();
  }, [isLoggedIn]);

  // 下载模板
  const handleDownloadTemplate = async () => {
    try {
      message.loading('正在准备下载模板...', 0);
      
      console.log('下载模板按钮已点击');
      
      const response = await menuAPI.downloadTemplate();
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `菜单导入模板.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success('模板下载成功');
    } catch (error) {
      console.error('下载模板失败:', error);
      message.destroy();
      message.error('下载模板失败: ' + (error.response?.data?.message || error.message));
    }
  };

  // 导入菜单
  const handleImport = () => {
    console.log('导入按钮已点击');
    message.info('请选择要导入的Excel文件');
    const input = document.createElement('input');
    input.type = 'file';
    input.accept = '.xlsx';
    input.style.display = 'none';
    document.body.appendChild(input);
    
    input.addEventListener('change', async (e) => {
      const file = e.target.files && e.target.files[0];
      if (!file) {
        document.body.removeChild(input);
        return;
      }
      
      try {
        message.loading('正在上传并验证...', 0);
        
        const validateResponse = await menuAPI.validateMenu(file);
        console.log('验证响应:', validateResponse);
        
        const { job_id } = validateResponse.data || {};
        if (!job_id) {
          message.destroy();
          message.error('验证失败：未返回任务ID');
          return;
        }
        
        message.destroy();
        message.success('文件上传成功，正在处理...');
        
      } catch (error) {
        console.error('导入失败:', error);
        message.destroy();
        message.error('导入失败: ' + (error.response?.data?.message || error.message));
      } finally {
        document.body.removeChild(input);
      }
    });
    
    input.click();
  };

  // 导出菜单
  const handleExport = async () => {
    try {
      message.loading('正在准备导出...', 0);
      
      const response = await menuAPI.exportMenu();
      const url = window.URL.createObjectURL(new Blob([response.data]));
      const link = document.createElement('a');
      link.href = url;
      link.setAttribute('download', `菜单数据.xlsx`);
      document.body.appendChild(link);
      link.click();
      document.body.removeChild(link);
      window.URL.revokeObjectURL(url);
      
      message.destroy();
      message.success('导出成功');
    } catch (error) {
      console.error('导出失败:', error);
      message.destroy();
      message.error('导出失败: ' + (error.response?.data?.message || error.message));
    }
  };

  return (
    <div style={{ padding: '24px' }}>
      <Title level={2}>菜单管理</Title>
      
      {/* 登录表单 */}
      {!isLoggedIn ? (
        <Card title="管理员登录">
          <div>
            <div style={{ marginBottom: '16px' }}>
              <label>邮箱：</label>
              <input 
                type="text" 
                value={loginForm.email} 
                onChange={(e) => setLoginForm({...loginForm, email: e.target.value})}
              />
            </div>
            <div style={{ marginBottom: '16px' }}>
              <label>密码：</label>
              <input 
                type="password" 
                value={loginForm.password} 
                onChange={(e) => setLoginForm({...loginForm, password: e.target.value})}
              />
            </div>
            <Button 
              type="primary" 
              onClick={handleLogin} 
              loading={loginLoading}
            >
              登录
            </Button>
          </div>
        </Card>
      ) : (
        <Card>
          <Space>
            <span>已登录</span>
            <Button onClick={handleLogout}>退出登录</Button>
          </Space>
        </Card>
      )}
      
      {/* 菜单操作 */}
      <Card title="菜单操作" style={{ marginTop: '24px' }}>
        <Space>
          <Button onClick={handleDownloadTemplate} disabled={!isLoggedIn}>下载模板</Button>
          <Button onClick={handleImport} disabled={!isLoggedIn}>导入</Button>
          <Button onClick={handleExport} disabled={!isLoggedIn}>导出</Button>
        </Space>
      </Card>
      
      {/* 菜单列表 */}
      <Card title="菜单列表" style={{ marginTop: '24px' }}>
        {loading ? (
          <div>加载中...</div>
        ) : menuItems.length > 0 ? (
          <div>
            <p>共 {menuItems.length} 个菜品</p>
            <ul>
              {menuItems.map((item, index) => (
                <li key={item.id || index}>
                  {item.name} - {typeof item.price === 'number' ? `¥${item.price.toFixed(2)}` : '价格未知'}
                </li>
              ))}
            </ul>
          </div>
        ) : (
          <div>暂无菜品数据</div>
        )}
      </Card>
    </div>
  );
};

export default FixedMenuPage;